<template>
  <page-header-wrapper>
    <page-tab-list>
      <div class="table-page-search-box">
        <a-form layout="inline">
          <a-row :gutter="24">
            <a-col :md="8" :sm="24">
              <a-form-item label="昵称">
                <a-input placeholder="请输入昵称" v-model="queryParam.nickname" allowClear></a-input>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="手机号">
                <a-input placeholder="请输入手机号" v-model="queryParam.mobile" allowClear></a-input>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="姓名">
                <a-input placeholder="请输入姓名" v-model="queryParam.name" allowClear></a-input>
              </a-form-item>
            </a-col>
          </a-row>
          <a-row :gutter="24">
            <a-col :md="8" :sm="24">
              <a-form-item label="等级">
                <a-select v-model="queryParam.level_id" allowClear>
                  <a-select-option :value="item.id" v-for="item in levelList" :key="item.id">
                    {{ item.name }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="推荐人">
                <a-input placeholder="请输入推荐人" v-model="queryParam.parent" allowClear></a-input>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="">
                <a-button type="primary" @click="tablePageChange(1)">查询</a-button>
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </page-tab-list>
    <a-card :bordered="false">
      <div class="table-operator" style="display: flex; justify-content: space-between">
        <span></span>
        <a-button type="primary" @click="addPop = true">+ 添加</a-button>
      </div>
      <a-table
        :rowKey="
          (r, i) => {
            return i
          }
        "
        :pagination="{
          total: this.totalCount,
          showSizeChanger: false,
          onChange: this.tablePageChange,
        }"
        :columns="columns"
        :data-source="list"
        :scroll="{ x: 'max-content' }"
      >
        <div slot="name" slot-scope="text, record">
          <div class="name">
            <div class="pic">
              <img :src="record.avatar" alt="" />
            </div>
            <div class="info">
              <span>{{ record.nickname }}</span>
            </div>
          </div>
        </div>

        <span slot="team_order_price" slot-scope="scope">
          <div
            class="link"
            @click="
              $router.push({
                path: `/plugins/shareholder/teamPerformance?user_id=${scope.user_id}`,
              })
            "
          >
            ¥{{ scope.team_order_price || '0.00' }}
          </div>
        </span>
        <span slot="mobile" slot-scope="scope"> {{ scope.name }} / {{ scope.mobile }} </span>
        <span slot="audit_time" slot-scope="text">
          {{ text > 0 ? $moment(text * 1000).format('YYYY-MM-DD HH:mm:ss') : '-' }}
        </span>
        <span slot="range_profit" slot-scope="text"> ￥{{ text || 0 }} </span>
        <span slot="holder_profit" slot-scope="text"> ￥{{ text || 0 }} </span>
        <span slot="level_one_count" slot-scope="text, scope" class="level_one_count" @click="showCount(scope)">
          {{ text }} （点击查看）
        </span>
        <div slot="action" slot-scope="text, scope">
          <div class="action">
            <a-button type="link" @click="editLevel(scope)" size="small">编辑</a-button>
            <span class="line"></span>
    <!--    <a-button type="link" @click="deleteHolder(scope)" size="small">删除</a-button>  -->
          </div>
        </div>
      </a-table>
    </a-card>

    <a-modal v-model="addPop" @ok="submitForm" title="添加" :afterClose="closeAddPop">
      <a-form-model ref="ruleForm" :model="form" :rules="rules" :label-col="{ span: 6 }" :wrapper-col="{ span: 14 }">
        <a-form-model-item label="选择用户" prop="nickName">
          <a-input :disabled="true" placeholder="请选择用户" v-model="form.nickName" style="width: 150px"></a-input>
          <a-button type="primary" style="margin-left: 10px" @click="openPop('add')">选择</a-button>
        </a-form-model-item>
        <a-form-model-item label="姓名" prop="name">
          <a-input v-model="form.name" placeholder="请输入名称" />
        </a-form-model-item>
        <a-form-model-item label="手机号" prop="mobile">
          <a-input v-model="form.mobile" placeholder="请输入手机号" />
        </a-form-model-item>
        <a-form-model-item label="地区" prop="area">
          <Address v-model="form.area"></Address>
        </a-form-model-item>
        <a-form-model-item label="详细地址" prop="address">
          <a-input v-model="form.address" placeholder="请输入详细信息" />
        </a-form-model-item>
      </a-form-model>
    </a-modal>

    <!-- 编辑股东等级的弹窗 -->
    <a-modal v-model="showEdit" @ok="editHolderLevel" title="编辑股东" :destroyOnClose="true" :afterClose="closeEdit">
      <a-form-model ref="editForm" :model="editForm" :label-col="{ span: 6 }" :wrapper-col="{ span: 14 }">
        <a-form-model-item label="股东等级" prop="level">
          <a-select v-model="editForm.level_id" placeholder="请选择股东等级">
            <a-select-option :value="item.id" v-for="item in levelList" :key="item.id" :disabled="item.is_disabled">
              {{ item.name }}</a-select-option
            >
          </a-select>
        </a-form-model-item>
        <!-- <template v-if="editForm.level_id >= out_level && editForm.raw_level_id < out_level">
          <a-form-model-item :label="'助力出局下级(' + out_num + ' 个)'">
            <SelectUser selectType="shareholder" :parentId="editForm.user_id" :defaultUser="out_users" dataType="muti" @userInfo="onUserInfo"></SelectUser>
          </a-form-model-item>
        </template> -->
        <a-form-model-item label="上级" prop="parent" help="尽量不要轻易修改关系，容易引起数据错误">
          <a-input v-model="oldParentName" :disabled="true" style="width: 150px"></a-input>
   <!--   <a-button type="primary" style="margin-left: 10px" @click="openPop('edit', 1)">选择</a-button>   -->
        </a-form-model-item>
          <a-form-model-item label="链动上级" prop="parent" help="尽量不要轻易修改关系，容易引起数据错误">
          <a-input v-model="parentName" :disabled="true" style="width: 150px"></a-input>
   <!--   <a-button type="primary" style="margin-left: 10px" @click="openPop('edit', 0)">选择</a-button>   -->
        </a-form-model-item> 
        <a-form-model-item label="区域代理">
          <a-select v-model="editForm.agent_type" placeholder="请选择区域代理">
            <a-select-option value="0"> 默认 </a-select-option>
            <a-select-option value="1"> 省 </a-select-option>
            <a-select-option value="2"> 市 </a-select-option>
            <a-select-option value="3"> 区 </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="佣金比例" prop="agent_rate" v-if="editForm.agent_type != 0">
          <a-input-number :min="0" :max="99.99" :step="0.01" v-model="editForm.agent_rate" style="width: 150px" />
        </a-form-model-item>
        <a-form-model-item label="地区" prop="area" v-if="editForm.agent_type != 0">
          <Address v-model="addressInfo"></Address>
        </a-form-model-item>
      </a-form-model>
    </a-modal>

    <!-- 更换上级的弹窗 -->
    <a-modal
      title="选择用户"
      zIndex="9999"
      style="width: 300px"
      v-model="userVisible"
      :destroyOnClose="true"
      :footer="null"
    >
      <div style="margin-bottom: 10px">
        <a-input-search
          placeholder="输入昵称搜索"
          v-model="keyword"
          allowClear
          enter-button
          @search="$refs.table.refresh(true)"
        />
      </div>
      <s-table ref="table" rowKey="id" :columns="manager" :data="loadData">
        <span slot="baseinfo" slot-scope="text, record">
          <img style="width: 40px; heigth: 40px; border-radius: 3px; margin-right: 5px" :src="record.avatar" />
          <span :length="20" tooltip>{{ record.name }}</span>
        </span>
        <span slot="action" slot-scope="text, record">
          <a-button type="primary" size="small" @click="onSelect(record)"> 选择 </a-button>
        </span>
      </s-table>
    </a-modal>
  </page-header-wrapper>
</template>

<script>
import storage from 'store'
import { Address, STable } from '@/components'
import SelectUser from '@/components/SelectUser/SelectUser1'
import { allLevel, list, editShareholder, shareHolderAdd } from '@/api/shareholder'
import { getSelectUserList } from '@/api/user'

const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
  },
  {
    title: '会员信息',
    scopedSlots: {
      customRender: 'name',
    },
    width: 200,
  },
  {
    title: '姓名/电话',
    scopedSlots: {
      customRender: 'mobile',
    },
  },
  {
    title: '团队业绩',
    scopedSlots: {
      customRender: 'team_order_price',
    },
  },
  {
    title: '等级',
    dataIndex: 'level_name',
  },
  {
    title: '极差佣金',
    dataIndex: 'range_profit',
    scopedSlots: {
      customRender: 'range_profit',
    },
  },
  {
    title: '股东分红佣金',
    dataIndex: 'holder_profit',
    scopedSlots: {
      customRender: 'holder_profit',
    },
  },
  {
    title: '推荐人',
    dataIndex: 'parent_name',
  },
  {
    title: '老推荐人',
    dataIndex: 'old_parent_name',
  },
  {
    title: '一级下级人数',
    dataIndex: 'level_one_count',
    scopedSlots: {
      customRender: 'level_one_count',
    },
  },
  // {
  //   title: '团队人数',
  //   dataIndex: 'level_count',
  // },
  {
    title: '成为股东时间',
    dataIndex: 'audit_time',
    scopedSlots: {
      customRender: 'audit_time',
    },
    sorter: (a, b) => a.audit_time - b.audit_time,
  },
  {
    title: '操作',
    dataIndex: 'action',
    scopedSlots: {
      customRender: 'action',
    },
  },
]
const manager = [
  {
    title: 'ID',
    dataIndex: 'id',
  },
  {
    title: '用户信息',
    scopedSlots: { customRender: 'baseinfo' },
  },
  {
    title: '操作',
    scopedSlots: { customRender: 'action' },
  },
]
export default {
  components: {
    STable,
    Address,
    SelectUser,
  },
  data() {
    return {
      // 搜索参数
      queryParam: {
        nickname: null,
        name: null,
        mobile: null,
        parent: null,
        level_id: null,
        pageNo: 1,
        pageSize: 10,
      },
      // 请求的数据列表
      list: [],
      // 表格列配置
      columns,
      manager,
      // 数据条数
      totalCount: 0,
      // 所有等级列表
      levelList: [],
      // 是否展示编辑股东的弹窗
      showEdit: false,
      keyword: '',
      // 编辑股东表单
      editForm: {
        id: 0,
        level_id: 0,
        saas_user_id: 0,
        old_saas_user_id: 0,
        // 区域代理等级 0默认 1省 2市 3区
        agent_type: '0',
        // 区域代理比例
        agent_rate: '',
      },
      // 编辑的上级名称
      parentName: '',
      // 编辑的老上级名称
      oldParentName: '',
      // 是否显示选择上级弹窗
      userVisible: false,
      // 选择用户数据加载
      loadData: (parameter) => {
        let { type } = this,
          params

        if (type === 'add') {
          params = {
            type: 'user',
            scene: 'shareHolder',
          }
        } else {
          params = {
            type: 'shareHolder',
          }
        }

        return getSelectUserList({
          ...parameter,
          ...params,
          storeId: storage.get('storeId'),
          keyword: this.keyword,
        }).then((res) => {
          return res.data
        })
      },
      // 地区信息
      addressInfo: {},

      // 添加
      addPop: false,
      rules: {
        nickName: [{ required: true, message: '请选择', trigger: 'change' }],
        name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
        mobile: [{ required: true, message: '请输入手机号', trigger: 'blur' }],
        area: [{ required: true, message: '请选择地区', trigger: 'blur' }],
        address: [{ required: true, message: '请输入详细地址', trigger: 'blur' }],
      },

      form: {
        nickName: '',
        mobile: '',
        name: '',
        area: {},
        address: '',
        user_id: '',
      },

      type: '', // edit add
      modalLoading: false,
      out_level: 0,
      out_num: 0,
      out_users: [],
    }
  },
  methods: {
    onUserInfo(e) {
      this.out_users = e
    },
    // 获取数据列表
    async getList() {
      const hide = this.$message.loading('加载中', 0)
      const res = await list(this.queryParam)
      if (res.code == 0) {
        this.totalCount = res.data.totalCount
        this.list = res.data.data
      }
      hide()
    },
    // 分页请求
    tablePageChange(e) {
      this.queryParam.pageNo = e
      this.getList()
    },
    // 获取所有等级列表
    async allLevel() {
      const res = await allLevel()
      if (res.code == 0) {
        this.levelList = res.data.list
        this.out_level = res.data.out_level
        this.out_num = res.data.out_num
        let to_level_id = 0
        //查询是否链动出局，并获取帮助出局的等级
        this.levelList.forEach((e) => {
          let condition = JSON.parse(e.condition)
          if (condition.shareholder && condition.shareholder.is_open && condition.shareholder.independent_team) {
            to_level_id = condition.shareholder.to_level_id
          }
        })
        if (to_level_id > 0) {
          this.levelList.forEach((e, i) => {
            this.levelList[i].is_disabled = 0
            if (parseInt(e.id) === parseInt(to_level_id)) {
              this.levelList[i].is_disabled = 1
            }
          })
        }
        console.log('levelList', this.levelList)
      }
    },
    // 关闭编辑等级弹框重置表单数据
    closeEdit() {
      this.editForm = {
        id: 0,
        level_id: 0,
        saas_user_id: 0,
        old_saas_user_id: 0,
        agent_type: '0',
        agent_rate: '',
      }
      this.addressInfo = {}
      this.showEdit = false
    },
    // 显示下级列表弹窗
    showCount(e) {
      this.$router.push('/plugins/shareholder/junior?id=' + e.user_id)
    },
    // 显示编辑股东等级的弹窗
    editLevel(e) {
      console.log(e)
      this.editForm.id = e.id
      this.editForm.level_id = e.level_id
      this.editForm.raw_level_id = e.level_id
      this.editForm.agent_type = e.agent_type
      this.editForm.agent_rate = e.agent_rate
      this.editForm.saas_user_id = e.parent_id
      this.editForm.old_saas_user_id = e.old_parent_id
      this.editForm.user_id = e.user_id
      this.parentName = e.parent_name
      this.oldParentName = e.old_parent_name
      let location = {
        province_id: e.province_id - 0,
        city_id: e.city_id - 0,
        district_id: e.district_id - 0,
      }
      this.addressInfo = location
      this.showEdit = true
    },
    // 修改股东等级
    editHolderLevel() {
      let param = {
        type: '2',
        id: this.editForm.id,
        value: this.editForm.level_id,
        saas_user_id: this.editForm.saas_user_id,
        old_saas_user_id: this.editForm.old_saas_user_id,
        agent_type: this.editForm.agent_type,
      }
      if (param.agent_type != 0) {
        param.agent_rate = this.editForm.agent_rate
        param.province_id = this.addressInfo.province_id
        param.city_id = this.addressInfo.city_id
        param.district_id = this.addressInfo.district_id
      }
      console.log(param)
      console.log(this.out_users)
      if (
        this.out_level > 0 &&
        this.editForm.level_id >= this.out_level &&
        this.editForm.raw_level_id < this.out_level
      ) {
        if (this.out_users.length < this.out_num) {
          this.$message.error(
            '请选择 ' +
              this.out_num +
              ' 个助力出局的下级股东, 目前还差 ' +
              (this.out_num - this.out_users.length) +
              ' 个'
          )
          return
        }
      }
      param.out_users = this.out_users
      param.is_out = this.editForm.level_id >= this.out_level
      this.editShareholder(param)
    },
    // 点击删除股东
    deleteHolder(e) {
      let that = this
      this.$confirm({
        title: '是否删除股东?',
        onOk() {
          that.editShareholder({
            type: '1',
            id: e.id,
          })
        },
        onCancel() {},
      })
    },
    // 编辑股东  修改 删除
    async editShareholder(param) {
      const res = await editShareholder(param)
      if (res.code == 0) {
        this.closeEdit()
        this.getList()
      }
    },
    // 选择用户
    onSelect(e) {
      let { type } = this
      if (type === 'edit') {
        if (this.parent_type == 1) {
          this.oldParentName = e.name
          this.editForm.old_saas_user_id = e.id
        } else {
          this.parentName = e.name
          this.editForm.saas_user_id = e.id
        }
      } else {
        this.form.nickName = e.name
        this.form.user_id = e.id

        this.$refs.ruleForm.validateField('nickName')
      }

      this.userVisible = false
    },

    submitForm() {
      if (this.modalLoading) return
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          let form = JSON.parse(JSON.stringify(this.form))

          if (!form.area.province_id) {
            this.$message.error('请选择省份')
            return
          }

          if (!form.area.city_id || form.area.city_id === 0) {
            this.$message.error('请选择城市')
            return
          }

          if (!form.area.district_id || form.area.district_id === 0) {
            this.$message.error('请选择区域')
            return
          }

          let params = {
            name: form.name,
            user_id: form.user_id,
            mobile: form.mobile,
            province: form.area.province_id,
            city: form.area.city_id,
            district: form.area.district_id,
            address: form.address,
          }

          this.modalLoading = true

          shareHolderAdd(params)
            .then((res) => {
              this.modalLoading = false
              this.addPop = false
              if (res.code === 0) {
                this.$message.success(res.msg)

                this.getList()
                this.userVisible = false
                return
              }

              this.$message.error(res.msg)
            })
            .catch((err) => {
              this.$message.error(err.message)
              this.modalLoading = false
            })
        }
      })
    },

    closeAddPop() {
      this.$refs.ruleForm.resetFields()
    },

    openPop(type, parent_type) {
      this.type = type
      this.parent_type = parent_type
      this.userVisible = true
    },
  },
  mounted() {
    this.allLevel()
    this.getList()
  },
}
</script>

<style lang="less" scoped>
.search {
  /deep/ .ant-card-body {
    padding-top: 0 !important;
    padding-bottom: 14px !important;
  }
}
.searchBox {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  /deep/ .ant-input-affix-wrapper {
    width: 220px;
    margin-top: 14px;
    margin-right: 20px;
  }
  .select {
    display: flex;
    align-items: center;
    margin-top: 14px;
    margin-right: 20px;
  }
  .ant-btn {
    margin-top: 14px;
  }
}
.name {
  display: flex;
  align-items: center;
  .pic {
    width: 48px;
    min-width: 48px;
    height: 48px;
    border-radius: 4px;
    overflow: hidden;
    margin-right: 24px;
    img {
      width: 100%;
      height: 100%;
    }
  }
  .info {
    flex: auto;
    width: 0;
    display: flex;
    flex-direction: column;
    font-size: 14px;
    span {
      width: 100%;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
    }
    span:nth-child(2) {
      color: rgba(0, 0, 0, 0.45);
      margin-top: 6px;
    }
  }
}
.action {
  display: flex;
  align-items: center;
  .line {
    width: 1px;
    height: 14px;
    background-color: #d8d8d8;
  }
}
.level_one_count {
  text-decoration: underline;
  cursor: pointer;
  color: #ff4400;
}

.link {
  text-decoration: underline;
  cursor: pointer;
  color: #ff4400;
}
</style>
